<template>
  <div
    class="title-box"
    :class="{
      border: border,
    }"
    :style="{ padding: padding }"
    @click="handleClick"
  >
    <div
      id="tLeft"
      :class="{
        bold: bold,
      }"
      :style="{
        color: color,
        fontSize: size,
      }"
    >
      <div ref="label">{{ label }}</div>
      <div
        class="borderBottom"
        :style="{
          width: bmWidth,
          backgroundColor: bottomColor,
        }"
      />
    </div>
    <My-btn
      v-if="rightText && !$slots.right"
      :label="rightText"
      size="14"
      width="96"
      @click="handleRight"
    />
    <slot name="right" />
    <slot name="custom" />
  </div>
</template>

<script>
export default {
  props: {
    // 标题文字
    label: {
      type: String,
      default: "",
      required: true,
    },
    // 标题颜色
    color: {
      type: String,
      default: "#000",
    },
    // 字体大小
    size: {
      type: String,
      default: "22px",
    },
    // 是否加粗
    bold: {
      type: [Boolean, String],
      default: true,
    },
    // 下划线颜色
    bottomColor: {
      type: String,
      default: "#466EC54D",
    },
    // 下划线宽度 (px)
    bottomWidth: {
      type: [String, Number],
      default: "auto",
    },
    // 下边框线
    border: {
      type: Boolean,
      default: false,
    },
    // 内边距
    padding: {
      type: String,
      default: "10px 0",
    },
    // 右侧文字 (优先级低于插槽)
    rightText: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      bmWidth: "",
    };
  },
  watch: {
    // 动态修改标题时改变宽度
    label() {
      this.setBottomWidth();
    },
  },
  mounted() {
    this.setBottomWidth();
  },
  methods: {
    setBottomWidth() {
      if (this.bottomWidth == "auto") {
        this.$nextTick(() => {
          let width = this.$refs.label.clientWidth;
          this.bmWidth = width + 10 + "px";
        });
      } else {
        this.bmWidth = this.bottomWidth + "px";
      }
    },
    // 整行点击事件 (会覆盖右侧事件)
    handleClick() {
      this.$emit("click");
    },
    // 右侧事件
    handleRight() {
      this.$emit("right");
    },
  },
};
</script>

<style lang="scss" scoped>
.title-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  span {
    position: relative;
    z-index: 1;
  }
  .borderBottom {
    position: absolute;
    left: 0;
    bottom: 10px;
    height: 10px;
    z-index: 0;
  }
  .title-right {
    font-size: 14px;
    width: 96px;
    height: 26px;
    line-height: 26px;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    text-align: center;
  }
}
.border {
  border-bottom: 1rpx solid #d9d9d999;
}
.bold {
  font-weight: 600;
}
</style>
